from flask import Flask, jsonify, request
import pandas as pd
import random

app = Flask(__name__)

# 读取CSV文件的函数
def read_csv():
    try:
        return pd.read_csv('lst-tbmb.csv', encoding='gbk')
    except Exception as e:
        print(f"读取CSV文件错误: {e}")
        return None

# API 1: 获取京东自营价为空的记录
@app.route('/get_empty_prices', methods=['GET'])
def get_empty_prices():
    df = read_csv()
    if df is None:
        return jsonify({"error": "无法读取CSV文件"}), 500
    
    # 找出京东自营价为空的行
    empty_prices = df[df['京东自营价'].isna()].copy()
    
    if empty_prices.empty:
        response = jsonify({
            "message": "没有找到京东自营价为空的记录",
            "code": 201
        })
        response.charset = 'utf-8'
        return response
    
    # 随机选择一条记录
    random_row = empty_prices.iloc[random.randint(0, len(empty_prices)-1)]
    
    # 构造搜索词（产品品牌 + 产品规格）
    search_term = str(random_row['产品品牌']) + str(random_row['产品规格'])
    
    response = jsonify({
        "id": int(random_row.name),  # 使用序号作为ID
        "search_term": search_term,
        "code": 200
    })
    response.charset = 'utf-8'
    return response

# API 2: 更新价格和链接
@app.route('/update_price', methods=['GET'])
def update_price():
    id = request.args.get('id', type=int)
    price = request.args.get('price')
    key = request.args.get('key', type=str)
    
    if id is None or price is None or key is None:
        return jsonify({"error": "缺少必要参数"}), 400
    
    try:
        df = read_csv()
        if df is None:
            response = jsonify({"error": "无法读取CSV文件"})
            response.charset = 'utf-8'
            return response, 500
        
        # 更新指定行的京东自营价和链接
        if price == "无数据":
            df.loc[id, '京东自营价'] = "无数据"
        else:
            try:
                df.loc[id, '京东自营价'] = float(price)
            except ValueError:
                df.loc[id, '京东自营价'] = None
                
        df.loc[id, '链接'] = key
        
        # 保存更新后的CSV文件
        df.to_csv('lst-tbmb.csv', index=False, encoding='gbk')
        
        response = jsonify({
            "message": "更新成功",
            "id": id,
            "price": price,
            "key": key
        })
        response.charset = 'utf-8'
        return response
        
    except Exception as e:
        response = jsonify({"error": f"更新失败: {str(e)}"})
        response.charset = 'utf-8'
        return response, 500

if __name__ == '__main__':
    app.run(debug=True, port=5000, host='192.168.31.76')
